package com.price.common.extend

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import androidx.annotation.NonNull
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import java.io.BufferedOutputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * 更改 bitmap 透明度
 * @param alpha     透明度
 * @param isRecycle 是否释放原图
 * @return 更改透明度后的 bitmap
 */
fun Bitmap.toAlpha(alpha:Int , isRecycle:Boolean=true):Bitmap {
    val paint = Paint()
    paint.alpha = alpha
    val descBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val c = Canvas(descBitmap)
    c.drawBitmap(this, 0f, 0f, paint)
    if (isRecycle) {
        recycle()
    }
    return descBitmap
}
/**
 * 缩放图片
 * @param scaleWidth  缩放宽度
 * @param scaleHeight 缩放高度
 * @return 缩放后的 bitmap
 */
fun Bitmap.createBitmap(scaleWidth:Float,scaleHeight:Float):Bitmap {
    val width = width
    val height = height
    val matrix = Matrix()
    matrix.postScale(scaleWidth, scaleHeight);
    return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}

/**
 * 保存图片到相册
 */
fun Bitmap.saveImageToGallery() {
    val appDir = File(Environment.getExternalStorageDirectory(), "COAL")
    if (!appDir.exists()) {
        appDir.mkdir()
    }
    val fileName = "coal_" + System.currentTimeMillis() + ".jpg"
    val file = File(appDir, fileName)
    var fos:FileOutputStream?=null
    try {
        fos = FileOutputStream(file)
        compress(Bitmap.CompressFormat.JPEG, 100, fos)
        fos.flush()
        fos.close()
    } catch (e:Exception) {
        doCustomCrashListener?.onCrash(e)
    }finally {
        kotlin.runCatching {
            fos?.close()
        }
    }
    MediaScannerConnection.scanFile(context,  arrayOf(file.toString()), null, null)
}

/**
 * 根据 Bitmap 转换成 Uri
 *
 * @param context 应用程序上下文
 * @return 转换后的 Uri
 */
fun Bitmap.bitmapToUri(context:Context):Uri {
    val bytes = ByteArrayOutputStream()
    compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    val path = MediaStore.Images.Media.insertImage(context.contentResolver, this, "Title", null)
    return Uri.parse(path)
}

/**
 * Drawable 转换成 bitmap
 * @return 转换后的 bitmap
 */
fun Drawable.drawableToBitmap():Bitmap {
    val width = intrinsicWidth
    val height = intrinsicHeight
    val config = if(opacity != PixelFormat.OPAQUE) Bitmap.Config.ARGB_8888
    else Bitmap.Config.RGB_565
    val bitmap = Bitmap.createBitmap(width, height, config)
    val canvas = Canvas(bitmap)
    setBounds(0, 0, width, height)
    draw(canvas)
    return bitmap
}

/**
 * bitmap 转换成 byte
 *
 * @return 转换后的 byte
 */
fun Bitmap.bitmapToBytes():ByteArray {
    val stream = ByteArrayOutputStream()
    compress(Bitmap.CompressFormat.PNG, 100, stream)
    return stream.toByteArray()
}

/**
 * 从View获取Bitmap
 *
 * @param view 文件路径
 * @return  返回 bitmap
 */
fun Bitmap.getBitmapFromView(view: View):Bitmap {
    val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    view.draw(canvas)
    return bitmap
}

/**
 * 按比例大小压缩Bitmap
 *
 * @param targetWidth 设置宽度
 * @param targetHeight 设置高度
 * @return  返回 bitmap
 */
fun Bitmap.compressByScale(targetWidth:Int, targetHeight:Int):Bitmap {
    return Bitmap.createScaledBitmap(this, targetWidth, targetHeight, true)
}

/**
 * 质量压缩图片
 * @param maxSize 200 kb
 * @return 压缩后的图片 byte 数组
 */
fun  Bitmap.compressImageByte(maxSize:Int=200):ByteArray {
    val baos = ByteArrayOutputStream()
    compress(Bitmap.CompressFormat.JPEG, 100, baos)
    var options = 90
    while (baos.toByteArray().size / 1024 > maxSize) {
        baos.reset()
        compress(Bitmap.CompressFormat.JPEG, options, baos)
        options -= 10
    }
    return baos.toByteArray()
}

/**
 * 获取 bitmap 大小
 * @return bitmap 的大小
 */
fun Bitmap.getBitmapBytes():Int {
    val result = byteCount
    if (result < 0) {
        throw IllegalStateException("Negative size: $this")
    }
    return result
}


/**
 * 根据图片路径获取 bitmap
 * @param filePath 图片文件路径
 * @return 对应的 bitmap
 */
fun Context.getBitmapByUrl(filePath:String):Bitmap? {
    val file = File(filePath)
    val uri = Uri.fromFile(file)
    var bitmap:Bitmap?= null
    try {
        bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, uri)
    } catch (e:IOException) {
        e.printStackTrace()
    }
    return bitmap
}

/**
 * bitmap 转文件
 * @param filePath 文件路径
 */
fun Bitmap.saveBitmapFile(filePath:String):String? {
    val file = File(filePath)
    var bos: BufferedOutputStream?= null
    try {
        bos =  BufferedOutputStream(FileOutputStream(file))
        this.compress(Bitmap.CompressFormat.JPEG, 100, bos)
        bos.flush()
    } catch (e: IOException) {
        doCustomCrashListener?.onCrash(e)
        return null
    } finally {
        if (bos != null) {
            try {
                bos.close()
            } catch (e:IOException) {
                e.printStackTrace()
            }
        }
    }
    return filePath
}

/**
 * 本地图片转化为Bitmap
 * @return  返回 bitmap
 */
fun String.getBitmapFromLocalPath():Bitmap {
    return BitmapFactory.decodeFile(this)
}
